package com.train.pattern.state.v1;


import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service("orderService")
public class OrderServiceImpl implements IOrderService {

    private int id = 1;
    private Map<Integer, Order> orders = new HashMap<>();

    @Override
    public Order create() {
        Order order = new Order();
        order.setStatus(OrderStatus.WAIT_PAYMENT);
        order.setId(id++);
        orders.put(order.getId(), order);
        return order;
    }

    @Override
    public Order pay(int id) {
        Order order = orders.get(id);
        System.out.println("线程名称：" + Thread.currentThread().getName() + " 尝试支付，订单号：" + id);

        if (OrderStatus.WAIT_PAYMENT.getCode().equals(order.getStatus().getCode())) {
            System.out.println("线程名称：" + Thread.currentThread().getName() + " 支付成功, 订单号：" + id);
            order.setStatus(OrderStatus.WAIT_DELIVER);
        } else if (OrderStatus.WAIT_DELIVER.getCode().equals(order.getStatus().getCode())) {
            System.out.println("线程名称：" + Thread.currentThread().getName() + " 支付失败, 订单号：" + id);

        } else if (OrderStatus.WAIT_DELIVER.getCode().equals(order.getStatus().getCode())) {
            System.out.println("线程名称：" + Thread.currentThread().getName() + " 支付失败, 订单号：" + id);
        } else {
            System.out.println("线程名称：" + Thread.currentThread().getName() + " 支付失败, 订单号：" + id);
        }
        return orders.get(id);
    }

    @Override
    public Order deliver(int id) {
        Order order = orders.get(id);
        System.out.println("线程名称：" + Thread.currentThread().getName() + " 尝试发货，订单号：" + id);

        if (OrderStatus.WAIT_DELIVER.getCode().equals(order.getStatus().getCode())) {
            System.out.println("线程名称：" + Thread.currentThread().getName() + " 发货成功, 订单号：" + id);
            order.setStatus(OrderStatus.WAIT_RECEIVE);
        }  else {
            System.out.println("线程名称：" + Thread.currentThread().getName() + " 发货失败，状态异常，订单号：" + id);
        }

        return orders.get(id);
    }

    @Override
    public Order receive(int id) {
        Order order = orders.get(id);
        System.out.println("线程名称：" + Thread.currentThread().getName() + " 尝试收货，订单号：" + id);

        if (OrderStatus.WAIT_RECEIVE.getCode().equals(order.getStatus().getCode())) {
            System.out.println("线程名称：" + Thread.currentThread().getName() + " 收货成功, 订单号：" + id);
            order.setStatus(OrderStatus.FINISH);
        }  else {
            System.out.println("线程名称：" + Thread.currentThread().getName() + " 收货失败，状态异常，订单号：" + id);
        }

        return orders.get(id);
    }


    @Override
    public Map<Integer, Order> getOrders() {
        return orders;
    }



}